//
//  YDOptionalViewController.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2017/11/3.
//  Copyright © 2017年 LK-IOS. All rights reserved.
//

#import "YDOptionalViewController.h"
#import "YDHomeMarketView.h"
#import "YDHomeMarketModel.h"
#import "YDOptionalTableViewCell.h"
#import "YDStockSearchViewController.h"
#import "YDOptionalEditingController.h"
#import "YDOptionalStockModel.h"//自选股票模型
#import "YDVerticalStockBuyController.h"
#import "YDStockMarketDetailController.h"
#import "YDOptionalTableHeaderView.h"
#import "YDOptionalNoDataView.h"

@interface YDOptionalViewController ()<UITableViewDelegate , UITableViewDataSource , SYHomeMarketViewDelegate , SYOptionalNoDataViewDelegate>
//无数据View
@property (nonatomic , weak) YDOptionalNoDataView *noDataView;

//tableView
@property (nonatomic , weak) UITableView *tableView;
//YDHomeMarketView
@property (nonatomic , weak) YDHomeMarketView *headerView;
//自选股票数组
@property (nonatomic , strong) NSMutableArray *optionalStockModel;
//大盘数据模型数组
@property (nonatomic , strong) NSMutableArray *marketModelArray;
//引导登录页面
@property (nonatomic, strong) SYGuideLoginView *guideLoginView;

//顶部安全区域
@property (nonatomic , assign) CGFloat safeTopH;
//底部安全区域
@property (nonatomic , assign) CGFloat safeBottomH;

//定时器
@property (nonatomic , strong) NSTimer *optionalTimer;
//是不是正在刷新
@property (nonatomic , assign) BOOL optionalTimerIsRunning;

//大盘数据
@property (nonatomic , strong) NSTimer *optionalMTimer;
//大盘数据是不是正在刷新
@property (nonatomic , assign) BOOL optionalMTimerIsRunning;

@end

@implementation YDOptionalViewController

-(NSMutableArray *)optionalStockModel
{
    if (_optionalStockModel == nil) {
        _optionalStockModel = [NSMutableArray array];
    }
    return _optionalStockModel;
}
-(NSMutableArray *)marketModelArray
{
    if (_marketModelArray == nil) {
        _marketModelArray = [NSMutableArray array];
    }
    return _marketModelArray;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = @"自选";
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    
    self.safeTopH = isPhoneX ? 84 : 64;
    self.safeBottomH = self.isHiddenTabbar ? 0 : (isPhoneX ? 83 : 49);
    
    
    [self setUpNavButton];
    [self tableView];
    [self setUpDataManger];
    
    [self addNotification];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if ([SYUserInformation sharedInstance].isLogin) {
        [self loadData];
    }else{
        [self removeTableView];
        [self removeNoDataView];
        self.navigationItem.leftBarButtonItem = nil;
        [self guideLoginView];
    }
    
    [self viewOpenTimer];
}
-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self removeNoDataView];
    [self removeGuideView];
    
    [self viewStopTimer];
}
-(void)viewOpenTimer
{
    if (self.optionalTimer && self.optionalMTimer)return;
    if (![NSDate stockTradingTimeJudgment])return;
    DDLog(@"PZOptionalViewController开启定时器")
    self.optionalTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadOptionalStockData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.optionalTimer forMode:NSRunLoopCommonModes];
    
    self.optionalMTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timeLoadMarketStockData) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.optionalMTimer forMode:NSRunLoopCommonModes];
}
-(void)viewStopTimer
{
    if (!self.optionalTimer && !self.optionalMTimer)return;
    
    DDLog(@"PZOptionalViewController关闭定时器")
    [self.optionalTimer invalidate];
    self.optionalTimer = nil;
    
    [self.optionalMTimer invalidate];
    self.optionalMTimer = nil;
}

//******开始通知*******//
-(void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewOpenTimer) name:UIApplicationDidBecomeActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewStopTimer) name:UIApplicationWillTerminateNotification object:nil];
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
//移除tableView
-(void)removeTableView
{
    if (_tableView) {
        [self.tableView removeFromSuperview];
        self.tableView = nil;
        self.headerView = nil;
    }
}
//添加tableView
-(void)addTableView
{
    [self tableView];
    [self setUpDataManger];
}
//移除无数据view
-(void)removeNoDataView
{
    if (_noDataView) {
        [self.noDataView removeFromSuperview];
        self.noDataView = nil;
    }
}

- (void)removeGuideView
{
    if (_guideLoginView) {
        [_guideLoginView removeFromSuperview];
        _guideLoginView = nil;
    }
}
//添加导航栏按钮
-(void)setUpNavButton
{
    UIBarButtonItem *rightItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"buy-search"] hightImage:[UIImage imageNamed:@"buy-search"] addTarget:self action:@selector(rightItemButtonClick:)];
    self.navigationItem.rightBarButtonItem = rightItemBtn;
}


- (void)addLeftNavigationBarItem
{
    UIBarButtonItem *leftItemBtn = [UIBarButtonItem imageWithNormalImage:[UIImage imageNamed:@"zx-bianji"] hightImage:[UIImage imageNamed:@"zx-bianji"] addTarget:self action:@selector(leftItemBtnClick:)];
    self.navigationItem.leftBarButtonItem = leftItemBtn;
}
-(void)leftItemBtnClick:(UIButton *)button
{
    if (self.optionalStockModel.count) {
        YDOptionalEditingController *vc = [[YDOptionalEditingController alloc] init];
        vc.optionalStockArray = self.optionalStockModel;
        vc.hidesBottomBarWhenPushed = YES;
        YDBaseNavigationController *nav = [[YDBaseNavigationController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                        WithType:NavTipsViewTypeMessage
                                                            text:@"暂无股票收藏"
                                                      isExistNav:YES];
    }
}
//进入搜索界面
-(void)rightItemButtonClick:(UIButton *)button
{
    [self popToSearchViewWithSearchString:@""];
}
-(void)setUpDataManger
{
    MJGIFHeader *header = [MJGIFHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    header.lastUpdatedTimeLabel.hidden = YES ;
    header.stateLabel.hidden = YES ;
    self.tableView.mj_header = header;
}
-(void)loadData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetOptionalStockList WithSuccessBlock:^(NSDictionary *resultDict) {
        if (_tableView) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.optionalStockModel removeAllObjects];
            
            self.optionalStockModel = [YDOptionalStockModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            
            [self removeGuideView];
            [self removeNoDataView];
            
            if (self.optionalStockModel.count) {
                [self addTableView];
                
                [self addLeftNavigationBarItem];
                [self.tableView reloadData];
                [self loadMarketData];
            }else{
                [self removeTableView];
                self.navigationItem.leftBarButtonItem = nil;
                [self noDataView];
            }
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view
                                                            WithType:NavTipsViewTypeMessage
                                                                text:@"信息加载出错，请重试~"
                                                          isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        if (_tableView) {
            [self.tableView.mj_header endRefreshing];
        }
        [self noDataView];
    }];
    
}
/*******加载大盘数据**********/
-(void)loadMarketData
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetMarketData WithSuccessBlock:^(NSDictionary *resultDict) {
        
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.marketModelArray removeAllObjects];
            self.marketModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self headerView];
            
            self.headerView.marketModelArray = self.marketModelArray;
            
            [self.tableView reloadData];
            
        }else{
        }
    } failBlock:^(NSError *error) {
    }];
    
}

/*******headerView**********/
-(YDHomeMarketView *)headerView
{
    if (_headerView == nil) {
        CGFloat headerViewH;
        if (isPhoneX) {
            headerViewH = rateX812(85);
        }else{
            headerViewH = rate750(85);
        }
        YDHomeMarketView *headerView = [YDHomeMarketView homeMarketViewMarketModelArray:self.marketModelArray];
        headerView.frame = CGRectMake(0, 0, LKScreenW, headerViewH);
        self.tableView.tableHeaderView = headerView;
        headerView.delegate = self;
        _headerView = headerView;
    }
    return _headerView;
}
/*******SYHomeMarketViewDelegate********/
-(void)homeMarketView:(YDHomeMarketView *)homeMarketView didSelectItemAtIndex:(NSInteger)index
{
    if (!self.marketModelArray.count)return;
    for (YDHomeMarketModel *model in self.marketModelArray) {
        model.isSelected = NO;
    }
    
    YDHomeMarketModel *model = self.marketModelArray[index];
    model.isSelected = YES;
    
    YDStockMarketDetailController *vc = [[YDStockMarketDetailController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.isNormal = YES;
    vc.marketModelArray = self.marketModelArray;
    vc.stockName = model.name;
    vc.stockCode = model .code;
    vc.index = index;
    [self.navigationController pushViewController:vc animated:YES];
}


/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        CGFloat tableH = LKScreenH - self.safeTopH - self.safeBottomH;
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, tableH) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        _tableView = tableView;
    }
    return _tableView;
}

#pragma UITableViewDelegate , UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.optionalStockModel.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(44) : rate750(44);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(56) : rate750(56);;
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YDOptionalTableHeaderView *headerView = [YDOptionalTableHeaderView headerViewWithTableView:tableView];
    return headerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDOptionalTableViewCell *cell = [YDOptionalTableViewCell cellWithTableView:tableView];
    
    
    YDOptionalStockModel *model = self.optionalStockModel[indexPath.row];
    
    
    cell.model = model;
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //跳转到点买界面
    YDOptionalStockModel *model = self.optionalStockModel[indexPath.row];
    YDVerticalStockBuyController *vc = [[YDVerticalStockBuyController alloc] init];
    vc.isNormal = YES;
    vc.isActivity = NO;
    vc.optionStyle = SYVerticalStockButtonOptionViewStyle3;
    vc.stockCode = model.code;
    vc.stockName = model.name;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -自定义删除 置顶
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *upAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"置顶" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        // 在最后希望cell可以自动回到默认状态，所以需要退出编辑模式
        
        tableView.editing = NO;
        if (indexPath.row == 0) {
            return;
        }
        
        YDOptionalStockModel *model = [self.optionalStockModel objectAtIndex:indexPath.row];
        
        
        [self upActionWithModels:self.optionalStockModel currentModel:model];
        
    }];
    upAction.backgroundColor = [UIColor colorWithHexString:frenchBlue];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        [self deleteActionWithIndexPath:indexPath];
    }];
    
    return @[deleteAction, upAction];
    
}



- (void)upActionWithModels:(NSMutableArray *)models currentModel:(YDOptionalStockModel *)model
{
    //    NSMutableArray *array = [NSMutableArray array];
    //    for (PZOptionalStockModel *model in models) {
    //        [array addObject:model.code];
    //    }
    
    //    NSString *IDs = [array componentsJoinedByString:@","];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:model.code forKey:@"stockCodes"];
    
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:TopOptionalStock WithSuccessBlock:^(NSDictionary *resultDict) {
        DDLog(@"%@",resultDict)
        DDLog(@"%@",resultDict[@"message"])
        
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.optionalStockModel removeObject:model];
            [self.optionalStockModel insertObject:model atIndex:0];
            [self.tableView reloadData];
            
        }else{
            
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"置顶未成功~" isExistNav:YES];
            
        }
    } failBlock:^(NSError *error) {
        DDLog(@"%@",error)
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"置顶未成功~" isExistNav:YES];
        
        
    }];
}


- (void)deleteActionWithIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *selectedStockArray = [NSMutableArray array];
    YDOptionalStockModel *model = [self.optionalStockModel objectAtIndex:indexPath.row];
    
    
    [selectedStockArray addObject:model.code];
    
    NSString *IDs = [selectedStockArray componentsJoinedByString:@","];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:IDs forKey:@"stockCodes"];
    [BaseNetRequest sessionRequestWithparameters:dict method:POSTMethod requstType:DeleteOptionalStock WithSuccessBlock:^(NSDictionary *resultDict) {
        
        
        if ([resultDict[@"code"] integerValue] == 200) {
            [self.optionalStockModel removeObjectAtIndex:indexPath.row];
            
            // 接着刷新view
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
            
            if (self.optionalStockModel.count == 0) {
                [self noDataView];
                [self removeTableView];
            }
            // 不需要主动退出编辑模式，上面更新view的操作完成后就会自动退出编辑模式
            
        }else{
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"删除未成功~" isExistNav:YES];
        }
    } failBlock:^(NSError *error) {
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"删除未成功~" isExistNav:YES];
    }];
    
}
//////*****无数据*****////////
-(YDOptionalNoDataView *)noDataView
{
    if (_noDataView == nil) {
        YDOptionalNoDataView *noDataView = [YDOptionalNoDataView optionalNoDataViewWithTitleArray:[NSArray array]];
        noDataView.frame = self.view.bounds;
        [self.view addSubview:noDataView];
        noDataView.delegate = self;
        _noDataView = noDataView;
    }
    return _noDataView;
}

-(SYGuideLoginView *)guideLoginView
{
    if (!_guideLoginView) {
        if (![SYUserInformation sharedInstance].isLogin) {
            //没有登录贴引导登录展位图
            
            _guideLoginView = [[SYGuideLoginView alloc] init];
            [self.view addSubview:_guideLoginView];
            [_guideLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.equalTo(self.view);
                make.top.equalTo(isPhoneX ? @(rateX812(40)) : @(rate750(40)));
            }];
            __weak typeof(self)weself = self;
            [_guideLoginView setClickBlock:^(BOOL isClick) {
                YDLoginController *loginVC = [[YDLoginController alloc] init];
                loginVC.loginStyle = Login_Present;
                YDBaseNavigationController *baseNav = [[YDBaseNavigationController alloc] initWithRootViewController:loginVC];
                [weself presentViewController:baseNav animated:YES completion:nil];
            }];
        }
    }
    return _guideLoginView;
}
/////*********SYOptionalNoDataViewDelegate******////
-(void)optionalNoDataView:(YDOptionalNoDataView *)dataView buttonStyle:(SYOptionalNoDataViewButtonStyle)style searchString:(NSString *)searchString
{
    if (style == SYOptionalNoDataViewStyleDefault) {
        [self popToSearchViewWithSearchString:searchString];
    }else{
        [self popToSearchViewWithSearchString:searchString];
    }
    
}


-(void)popToSearchViewWithSearchString:(NSString *)searchString
{
    YDStockSearchViewController *vc = [[YDStockSearchViewController alloc] init];
    vc.searchString = searchString;
    vc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
}

//定时加载信息
-(void)timeLoadOptionalStockData
{
    if (self.optionalTimerIsRunning || !self.optionalStockModel.count)return;
    self.optionalTimerIsRunning = YES;
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetOptionalStockList WithSuccessBlock:^(NSDictionary *resultDict) {
        
        self.optionalTimerIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            
            
            NSMutableArray *oldData = [NSMutableArray new];
            
            oldData = [self.optionalStockModel copy];
            
            [self.optionalStockModel removeAllObjects];
            
            self.optionalStockModel = [YDOptionalStockModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self.tableView reloadData];
            
            if (!self.optionalStockModel.count || !oldData.count) {
                return ;
            }
            for (int i  = 0; i < self.optionalStockModel.count; i++) {
                YDOptionalStockModel *newModel = [self.optionalStockModel objectAtIndex:i];
                
                YDOptionalStockModel *oldModel = [oldData objectAtIndex:i];;
                
                NSInteger newPrice = [[newModel.lastPrice stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
                NSInteger oldPrice = [[oldModel.lastPrice stringByReplacingOccurrencesOfString:@"." withString:@""] integerValue];
                
                if (newPrice > oldPrice) {
                    [self startAnimationWithRow:i isUp:YES];
                    continue;
                }else if(newPrice < oldPrice)
                {
                    [self startAnimationWithRow:i isUp:NO];
                    continue;
                }else
                {
                    continue;
                    //价格不变 不做处理
                }
            }
            
            
        }else{
        }
    } failBlock:^(NSError *error) {
        self.optionalTimerIsRunning = NO;
    }];
}
-(void)timeLoadMarketStockData
{
    if (self.optionalMTimerIsRunning || !self.optionalStockModel.count)return;
    self.optionalMTimerIsRunning = YES;
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetMarketData WithSuccessBlock:^(NSDictionary *resultDict) {
        self.optionalMTimerIsRunning = NO;
        if ([resultDict[@"code"] integerValue] == 200) {
            
            [self.marketModelArray removeAllObjects];
            self.marketModelArray = [YDHomeMarketModel mj_objectArrayWithKeyValuesArray:resultDict[@"result"]];
            [self headerView];
            
            self.headerView.marketModelArray = self.marketModelArray;
            
            [self.tableView reloadData];
            
        }else{
        }
    } failBlock:^(NSError *error) {
        self.optionalMTimerIsRunning = NO;
    }];
}

- (void)startAnimationWithRow:(NSInteger)index isUp:(BOOL)isUp;
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    YDOptionalTableViewCell*cell = (YDOptionalTableViewCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    [UIView animateWithDuration:1
                          delay:0
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         
                         cell.bgView.backgroundColor = [UIColor colorWithHexString:isUp ? @"#FFE8E5" :@"#E2F6DB"];
                         cell.bgView.alpha = 0.8;
                         
                         
                     } completion:^(BOOL finished) {
                         
                         [UIView animateWithDuration:1 animations:^{
                             cell.bgView.backgroundColor = [UIColor whiteColor];
                             cell.bgView.alpha = 1;
                         }];
                         
                     }];
    
    
}
@end
